package cn.iocoder.yudao.module.erp.controller.admin.relationship;

import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.erp.controller.admin.relationship.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.relationship.RelationshipDO;
import cn.iocoder.yudao.module.erp.service.relationship.RelationshipService;

@Tag(name = "管理后台 - 物料供应商关联")
@RestController
@RequestMapping("/erp/relationship")
@Validated
public class RelationshipController {

    @Resource
    private RelationshipService relationshipService;

    @PostMapping("/create")
    @Operation(summary = "创建物料供应商关联")
    @PreAuthorize("@ss.hasPermission('spd:relationship:create')")
    public CommonResult<Long> createRelationship(@Valid @RequestBody RelationshipSaveReqVO createReqVO) {
        List<String> relation = relationshipService.selectRelation(createReqVO.getProductId());
        RelationshipSaveReqVO rs = new RelationshipSaveReqVO();
        if (relation.size() > 0) {
            relationshipService.deleteRelation(createReqVO.getProductId());
        }
        for (ErpSupplierDO product : createReqVO.getSupplierIds()) {
            Long productId = product.getId();
            rs.setSupplierId(productId);
            rs.setProductId(createReqVO.getProductId());
            if(product.getIsDefault() != true){
                rs.setSort(0);
            }else if(product.getIsDefault() == true){
                rs.setSort(1);
            }
            rs.setMinOrderQuantity(product.getMinOrderQuantity());
            relationshipService.createRelationship(rs);
        }
        return success(createReqVO.getId());
    }


    @GetMapping("/getSupplie")
    @Operation(summary = "获得产品")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('spd:relationship:query')")
    public CommonResult<List<RelationshipRespVO>> getSupplie(@RequestParam("id") Long id) {
        List<RelationshipRespVO> product = relationshipService.getSupplie(id);
        return success(product);
    }

    @PutMapping("/update")
    @Operation(summary = "更新物料供应商关联")
    @PreAuthorize("@ss.hasPermission('spd:relationship:update')")
    public CommonResult<Boolean> updateRelationship(@Valid @RequestBody RelationshipSaveReqVO updateReqVO) {
        relationshipService.updateRelationship(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除物料供应商关联")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('spd:relationship:delete')")
    public CommonResult<Boolean> deleteRelationship(@RequestParam("id") Long id) {
        relationshipService.deleteRelationship(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得物料供应商关联")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('spd:relationship:query')")
    public CommonResult<RelationshipRespVO> getRelationship(@RequestParam("id") Long id) {
        RelationshipDO relationship = relationshipService.getRelationship(id);
        return success(BeanUtils.toBean(relationship, RelationshipRespVO.class));
    }

    @GetMapping("/getByIds")
    @Operation(summary = "获得物料供应商关联")
    @Parameter(name = "ids", description = "编号", required = true, example = "1024")
    public CommonResult<List<RelationshipRespVO>> getRelationships(List<Long> ids) {
        List<RelationshipDO> relationships = relationshipService.getRelationships(ids);
        return success(BeanUtils.toBean(relationships, RelationshipRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得物料供应商关联分页")
    @PreAuthorize("@ss.hasPermission('spd:relationship:query')")
    public CommonResult<PageResult<RelationshipRespVO>> getRelationshipPage(@Valid RelationshipPageReqVO pageReqVO) {
        PageResult<RelationshipDO> pageResult = relationshipService.getRelationshipPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RelationshipRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出物料供应商关联 Excel")
    @PreAuthorize("@ss.hasPermission('spd:relationship:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRelationshipExcel(@Valid RelationshipPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RelationshipDO> list = relationshipService.getRelationshipPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "物料供应商关联.xls", "数据", RelationshipRespVO.class,
                BeanUtils.toBean(list, RelationshipRespVO.class));
    }

    // ==================== 子表（物料字典） ====================

    @GetMapping("/product/get-by-id")
    @Operation(summary = "获得物料字典")
    @Parameter(name = "id", description = "产品编号")
    @PreAuthorize("@ss.hasPermission('spd:relationship:query')")
    public CommonResult<ErpProductDO> getProductById(@RequestParam("id") Long id) {
        return success(relationshipService.getProductById(id));
    }

    // ==================== 子表（供应商管理） ====================

    @GetMapping("/supplier/get-by-id")
    @Operation(summary = "获得供应商管理")
    @Parameter(name = "id", description = "供应商编号")
    @PreAuthorize("@ss.hasPermission('spd:relationship:query')")
    public CommonResult<ErpSupplierDO> getSupplierById(@RequestParam("id") Long id) {
        return success(relationshipService.getSupplierById(id));
    }

}